﻿using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Xml.Linq;

namespace NativeCode.Core.Extensions
{
	public static class SerializationExtensions
	{
		public static T FromJson<T>(this string data)
		{
			DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
			using (MemoryStream stream = new MemoryStream())
			{
				return (T)serializer.ReadObject(stream);
			}
		}

		public static T FromXml<T>(this XElement xml)
		{
			return xml.ToString().FromXmlString<T>();
		}

		public static T FromXmlString<T>(this string data)
		{
			DataContractSerializer serializer = new DataContractSerializer(typeof(T));
			using (MemoryStream stream = new MemoryStream())
			{
				return (T)serializer.ReadObject(stream);
			}
		}

		public static string ToJson<T>(this T instance)
		{
			DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
			using (MemoryStream stream = new MemoryStream())
			{
				serializer.WriteObject(stream, instance);
				stream.Position = 0;
				using (StreamReader reader = new StreamReader(stream))
				{
					return reader.ReadToEnd();
				}
			}
		}

		public static XElement ToXml<T>(this T instance)
		{
			return XElement.Parse(instance.ToXmlString());
		}

		public static string ToXmlString<T>(this T instance)
		{
			DataContractSerializer serializer = new DataContractSerializer(typeof(T));
			using (MemoryStream stream = new MemoryStream())
			{
				serializer.WriteObject(stream, instance);
				stream.Position = 0;
				using (StreamReader reader = new StreamReader(stream))
				{
					return reader.ReadToEnd();
				}
			}
		}
	}
}